import axios from 'axios'
import {message} from 'antd';

axios.defaults.timeout = 5000

// 请求拦截器
axios.interceptors.request.use(request => {
  // request.isInternal = request.url.startsWith('/api/');
  // if (request.isInternal) {
  //   request.headers['X-Token'] = X_TOKEN
  // }
  if (!request.headers) {
    request.headers = {}
  }
  // request.headers[AUTH_TOKEN] = ''
  request.timeout = request.timeout || 30000;
  return request;
});

// 返回拦截器
axios.interceptors.response.use(response => {
  return handleResponse(response)
}, error => {
  console.log(error)
  if (error.response) {
    return handleResponse(error.response)
  }
  const result = '请求异常: ' + error.message;
  return message.error(result);
});

// response处理
function handleResponse(response: any) {
  if (response.status === 401) {
    handle401Response(null)
    return Promise.reject()
  }

  if (response.status === 403) {
    return message.warning('权限不足！');
  }

  if (response.status !== 200) {
    return message.error(`请求失败: ${response.status} ${response.statusText}`);
  }

  const data = response.data;
  console.log(data)

  if (data.code === 0) {
    return Promise.resolve(data)
  }

  if (data.code === 401) {
    handle401Response(data)
    return Promise.reject()
  }

  if (data.code === 403) {
    return message.warning('权限不足！');
  }

  if (response.data.hasOwnProperty('data')) {
    return Promise.resolve(data)
  } else if (response.headers['content-type'] === 'application/octet-stream') {
    return Promise.resolve(response)
  }

  return message.error('数据格式不对');
}

function handle401Response(data: any) {
  return message.warning(data.message);
  // navigate("/login", {replace: true});
}

export default axios;
